/**
 * 本地同行服务计数修复脚本
 * 使用 Node.js 和 Prisma 执行数据修复
 */

const { prisma } = require('../config/prisma');

async function fixLocalServiceCounts() {
  console.log('开始修复本地同行服务计数数据...');
  
  try {
    // 获取所有服务
    const services = await prisma.local_services.findMany({
      select: { id: true }
    });
    
    console.log(`找到 ${services.length} 个服务需要检查`);
    
    let fixedLikes = 0;
    let fixedComments = 0;
    
    // 逐个修复每个服务的计数
    for (const service of services) {
      // 获取实际的点赞数量
      const actualLikeCount = await prisma.local_service_likes.count({
        where: { service_id: service.id }
      });
      
      // 获取实际的评论数量
      const actualCommentCount = await prisma.local_service_comments.count({
        where: { service_id: service.id }
      });
      
      // 获取当前存储的计数
      const currentService = await prisma.local_services.findUnique({
        where: { id: service.id },
        select: { like_count: true, comment_count: true }
      });
      
      // 检查是否需要更新
      const needsUpdate = 
        currentService.like_count !== actualLikeCount || 
        currentService.comment_count !== actualCommentCount;
      
      if (needsUpdate) {
        await prisma.local_services.update({
          where: { id: service.id },
          data: {
            like_count: actualLikeCount,
            comment_count: actualCommentCount,
            updated_at: new Date()
          }
        });
        
        if (currentService.like_count !== actualLikeCount) {
          fixedLikes++;
          console.log(`服务 ${service.id}: 点赞数 ${currentService.like_count} -> ${actualLikeCount}`);
        }
        
        if (currentService.comment_count !== actualCommentCount) {
          fixedComments++;
          console.log(`服务 ${service.id}: 评论数 ${currentService.comment_count} -> ${actualCommentCount}`);
        }
      }
    }
    
    // 获取修复后的统计信息
    const stats = await prisma.local_services.aggregate({
      _sum: {
        like_count: true,
        comment_count: true
      },
      _count: {
        id: true
      }
    });
    
    // 验证数据一致性
    const totalLikes = await prisma.local_service_likes.count();
    const totalComments = await prisma.local_service_comments.count();
    
    console.log('\n=== 修复完成 ===');
    console.log(`修复了 ${fixedLikes} 个服务的点赞计数`);
    console.log(`修复了 ${fixedComments} 个服务的评论计数`);
    console.log(`总服务数: ${stats._count.id}`);
    console.log(`总点赞数: ${stats._sum.like_count} (实际记录: ${totalLikes})`);
    console.log(`总评论数: ${stats._sum.comment_count} (实际记录: ${totalComments})`);
    
    // 验证一致性
    const isConsistent = 
      stats._sum.like_count === totalLikes && 
      stats._sum.comment_count === totalComments;
    
    console.log(`数据一致性: ${isConsistent ? '✅ 一致' : '❌ 不一致'}`);
    
    if (!isConsistent) {
      console.error('警告: 数据仍然不一致，请检查数据库状态');
    }
    
  } catch (error) {
    console.error('修复过程中发生错误:', error);
    throw error;
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  fixLocalServiceCounts()
    .then(() => {
      console.log('修复完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('修复失败:', error);
      process.exit(1);
    });
}

module.exports = { fixLocalServiceCounts };